package com.presto.directo.utils

import android.Manifest
import android.content.*
import android.content.pm.PackageManager
import android.database.Cursor
import android.provider.CalendarContract
import android.provider.CalendarContract.*
import androidx.core.app.ActivityCompat
import com.presto.directo.entity.*
import kotlinx.coroutines.*
import java.util.*

object CalendarUtil {

    fun getCalendarId(context: Context): String {
        var cursor: Cursor? = null
        return try {
            cursor = context.contentResolver.query(Calendars.CONTENT_URI, null, null, null, null)!!
            cursor.moveToFirst()
            cursor.getString(cursor.getColumnIndex(Calendars._ID))
        } catch (e: Exception) {
            ""
        } finally {
            cursor?.close()
        }

    }

    suspend fun getList(context: Context): List<CalendarModel> {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
            return listOf()
        }
        return withContext(Dispatchers.IO) {
            val list = arrayListOf<CalendarModel>()
            var cursor: Cursor? = null
            try {
                cursor = context.contentResolver.query(Events.CONTENT_URI, null, Events.CALENDAR_ID + "=" + getCalendarId(context), null, null)!!
                while (cursor.moveToNext()) {
                    val id = cursor.getString(cursor.getColumnIndex(Events._ID)) ?: ""
                    val title = cursor.getString(cursor.getColumnIndex(Events.TITLE)) ?: ""
                    val des = cursor.getString(cursor.getColumnIndex(Events.DESCRIPTION)) ?: ""
                    val start = cursor.getLong(cursor.getColumnIndex(Events.DTSTART)).toString()
                    val end = cursor.getLong(cursor.getColumnIndex(Events.DTEND)).toString()
                    val calendarModel = CalendarModel(id, title, des, start, end, getReminderList(context, id))
                    list.add(calendarModel)
                }
                list
            } catch (e: Exception) {
                list
            } finally {
                cursor?.close()
            }
        }
    }

    /*1:METHOD_ALERT
    2:METHOD_DEFAULT
    3:METHOD_EMAIL
    4:METHOD_SMS*/
    private fun getReminderList(context: Context, eventId: String): List<ReminderModel> {
        val list = arrayListOf<ReminderModel>()
        var cursor: Cursor? = null
        return try {
            cursor = context.contentResolver.query(Reminders.CONTENT_URI, null, Reminders.EVENT_ID + "=" + eventId, null, null)!!
            while (cursor.moveToNext()) {
                val rId = cursor.getString(cursor.getColumnIndex(Reminders._ID)) ?: ""
                val minutes = cursor.getString(cursor.getColumnIndex(Reminders.MINUTES)) ?: ""
                var method = cursor.getString(cursor.getColumnIndex(Reminders.METHOD)) ?: ""
                method = when (method) {
                    "0" -> "2"
                    "2" -> "3"
                    "3" -> "4"
                    else -> method
                }
                val reminderModel = ReminderModel(eventId, method, minutes, rId)
                list.add(reminderModel)
            }
            list
        } catch (e: Exception) {
            list
        } finally {
            cursor?.close()
        }
    }

    fun add(context: Context) {
        val cId = CalendarUtil.getCalendarId(context)
        if (cId.isNotBlank()) {
            val contentValues = ContentValues()
            contentValues.put("title", "上传身份证")
            contentValues.put("calendar_id", cId)
            val start = getStartTime()
            val end = start + 5 * 60 * 1000L
            contentValues.put(CalendarContract.Events.DTSTART, start)
            contentValues.put(CalendarContract.Events.DTEND, end)
            contentValues.put(CalendarContract.Events.HAS_ALARM, 1)
            contentValues.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().id)
            val eventUri = context.contentResolver.insert(CalendarContract.Events.CONTENT_URI, contentValues) ?: return
            val remind = ContentValues()
            remind.put(CalendarContract.Reminders.EVENT_ID, ContentUris.parseId(eventUri))
            remind.put(CalendarContract.Reminders.MINUTES, 0)
            context.contentResolver.insert(CalendarContract.Reminders.CONTENT_URI, remind)
        }
    }

    fun getStartTime(): Long {
        val current = System.currentTimeMillis()
        val day = current.formatTime("yyyy-MM-dd")
        val todayNine = day.parseTime("yyyy-MM-dd") + 21 * 60 * 60 * 1000L
        if (current < todayNine) {
            return todayNine
        } else {
            return todayNine + 24 * 60 * 60 * 1000L
        }
    }
}